package com.vmix.vmixmobiledemo;

import com.vmix.android.vmixsdk.rds.PlayVideoService;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Window;
import android.widget.VideoView;
import android.widget.MediaController;
import android.net.Uri;

public class VideoPlaybackActivity extends Activity {
	
	/**
	 * holds the video location
	 */
	private String playUrl;
	private String playToken;
	
	private IntentFilter filter = null;
	private PlayVideoReceiver receiver = null;
	
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.videoview);
		
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		// get the damn token from the intent
		this.playToken = bundle.getString( "playToken" );
		
		// register intent receiver
		this.filter = new IntentFilter( PlayVideoService.PLAY_URL_FOUND );
		// set up receiver
		this.receiver = new PlayVideoReceiver();
		
		registerReceiver(this.receiver, this.filter);

		// start service
		this.startPlayVideoService();
	}
	
	@Override
	public void onDestroy()
	{
		super.onDestroy();
	
		// unregister receiver
		unregisterReceiver( this.receiver );
		
		// stopping service
		this.stopPlayVideoService();
	}
	
    /**
     * Extend broadcast receiver to listen only to messages from GetCollectionMediasReceiver
     * 
     * @author lei
     *
     */
    public class PlayVideoReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {

			// get the playUrl from the intent
			Bundle bundle = intent.getExtras();
			
			playUrl = bundle.getString( "playUrl" );
			
			// play video
			playVideo();
			
		}
    	
    }
	
    /**
     * execute playvideoservice to get back the url
     */
    private void startPlayVideoService() {
    	// create intent
    	Intent intent = new Intent(this, PlayVideoService.class );
    	intent.putExtra( "playToken", this.playToken);
    	
    	// start service
    	startService( intent );
    }
    
    private void stopPlayVideoService() {
    	
    	stopService( new Intent( this, PlayVideoService.class) );
    	
    }
	/**
	 * move the video playing functionality into private method
	 */
	private void playVideo() {
		
		VideoView video = (VideoView) findViewById(R.id.video);
		
		// parse url
		video.setVideoURI(Uri.parse( this.playUrl ) );
		
		// set Media Controller
		video.setMediaController(new MediaController(this));
		video.requestFocus();
		// start view
		video.start();
	}
}
